<template>
  <div class="weather-container">
    <div>
      <div v-if="localCityData.forecasts && localCityData.forecasts.length > 0">
        <div
          v-for="(forecast, index) in localCityData.forecasts"
          :key="index"
          class="forecast-item"
        >
          <div
            v-for="(cast, castIndex) in forecast.casts"
            :key="castIndex"
            class="cast-item"
          >
            <div>{{ combinedDates[castIndex] }}</div>
            <!-- 使用合并的星期 -->
            <div>{{ cast.date }}</div>
            <div>天气: {{ cast.dayweather }}</div>
            <div>风力: {{ cast.daypower }}级</div>
          </div>
        </div>
      </div>
      <div v-else>
        <p>暂无天气数据</p>
      </div>
    </div>
    <WeatherChart
      :xData="xData"
      :dayTemps="dayTemps"
      :nightTemps="nightTemps"
      class="weather-chart"
    />
    <!-- <MyChart /> -->
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
import WeatherChart from "./WeatherChart.vue"; // 引入 WeatherChart 组件
// import MyChart from '@/components/MyChart.vue'

const props = defineProps({
  localCityData: {
    type: Object,
    required: true,
  },
});

// 初始化日期数组
const date = ["今天", "明天"];
const combinedDates = ref([]);

// 图表所需数据
const xData = ref([]);
const dayTemps = ref([]);
const nightTemps = ref([]);

// 观察 localCityData 的变化
watch(
  () => props.localCityData,
  (newValue) => {
    if (newValue.forecasts && newValue.forecasts.length > 0) {
      const casts = newValue.forecasts[0].casts;
      const weeks = casts.map((cast) => cast.week);
      const weekDays = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
      const newWeekDays = weeks.map((week) => {
        const dayIndex = parseInt(week, 10) + 1;
        return weekDays[dayIndex];
      });
      combinedDates.value = [...date, ...newWeekDays];

      // 清空 xData、dayTemps 和 nightTemps 数组
      xData.value = [];
      dayTemps.value = [];
      nightTemps.value = [];

      // 提取日期和气温
      casts.forEach((cast) => {
        xData.value.push(cast.date); // 日期
        dayTemps.value.push(Number(cast.daytemp)); // 将白天气温转为数值
        nightTemps.value.push(Number(cast.nighttemp)); // 将夜间气温转为数值
      });
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.weather-container {
  margin-top: 30px;
  padding: 0 10%;
  background: #004e71;
}

.forecast-item {
  display: flex;
  justify-content: space-between;
}

.cast-item {
  text-align: center;
  color: white;
  line-height: 50px;
}

.weather-title {
  color: white;
}
.weather-chart {
  height: 300px;
}
</style>
